package de.ret_world.openrpgstudio.mapeditor.tools;

import de.ret_world.openrpgstudio.editor.script.Point;
import de.ret_world.openrpgstudio.mapeditor.MapEditorWidget;
import de.ret_world.openrpgstudio.mapeditor.MapToolPlugin;
import de.ret_world.openrpgstudio.mapeditor.Pointer;
import de.ret_world.openrpgstudio.mapeditor.TileSetWidget;
import java.util.ArrayList;

/**
 * A simple Brush for painting Tiles
 *
 * @author Emu
 */
public class BrushTool extends MapToolPlugin {

    public BrushTool(TileSetWidget tileSetWidget, MapEditorWidget mapEditorWidget) {
        super(tileSetWidget, mapEditorWidget);
    }

    @Override
    public void use(int x, int y, int TYPE) {
        if (TYPE == CLICKED) {
            ArrayList<Pointer> pointers = mapEditorWidget.getPointers();
            if (pointers != null && !pointers.isEmpty()) {
                for (Pointer p : pointers) {
                    mapEditorWidget.setTile(p);
                }
            }
        } else {
            ArrayList<Integer> selectedTiles = tileSetWidget.getSelectedTiles();
            if (selectedTiles != null && !selectedTiles.isEmpty()) {
                int index = selectedTiles.get(0);
                hover(x, y);
                mapEditorWidget.setTile(x, y, index);
            }
        }
    }

    @Override
    public String activeText() {
        return "[B]";
    }

    @Override
    public String inactiveText() {
        return "B";
    }

    @Override
    public void activated() {
    }

    @Override
    public void hover(int x, int y) {
        ArrayList<Integer> selectedTiles = tileSetWidget.getSelectedTiles();
        if (selectedTiles != null && !selectedTiles.isEmpty()) {
            int index = selectedTiles.get(0);
            Pointer pointer = mapEditorWidget.setPointer(x, y, index);
            if (selectedTiles.size() > 1) {
                Point p = pointer.getPoint();
                int sy = 0;
                int sx = 1;

                int width = tileSetWidget.getSelectedTilesWidth();

                if (width == 1) {
                    sy = 1;
                    sx = 0;
                }
                for (int i = 1; i < selectedTiles.size(); i++) {
                    mapEditorWidget.addPointer(new Pointer(new Point(p.getX() + sx, p.getY() + sy), selectedTiles.get(i)));

                    sx++;
                    if (!(sx < width)) {
                        sy++;
                        sx = 0;
                    }
                }
            }
        }
    }
}
